package dieciLuglio;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.net.*;
import java.security.Key;
import java.security.KeyPair;
import java.util.*;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;


public class Inviatore {

	BufferedReader br=null;
	PrintWriter pr=null;
	ObjectInputStream input=null;
	Socket socket;
	private static InputStream keyReceive;
	private static OutputStream keySend;
	private Key chiaveDES;
	static String  indirizzo="localhost";
	
	public static void setInviatore (String s){
		indirizzo=s;
	}
	public Inviatore(){
		
		try {
			socket=new Socket(indirizzo,3001);
			System.out.println("inviatore partito");
			OutputStreamWriter osw=new OutputStreamWriter(socket.getOutputStream());
			BufferedWriter br1=new BufferedWriter(osw);
			pr=new PrintWriter(br1,true);
			
			InputStreamReader isr = new InputStreamReader(socket.getInputStream());
			br = new BufferedReader(isr);
			
			keyReceive=socket.getInputStream();
			keySend=socket.getOutputStream();
			chiaveDES=scambioChiavi();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public Key scambioChiavi()throws Exception{
		//generazione chiavi RSA
		KeyPair keyRsa=RSA.generaChiave();
		
		//invio chiave RSA pubblica tramite outstream
		keySend.write(keyRsa.getPublic().getEncoded());
		
		//Ricezione e decriptazione chiave DES ,creata da ServerThread, tramite chiave privata RSA
		byte[] DESKeyByte=new byte[1000];
		int numByte=keyReceive.read(DESKeyByte);
		DESKeyByte=Arrays.copyOf(DESKeyByte, numByte);
		Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
		
		
		cipher.init(Cipher.DECRYPT_MODE, keyRsa.getPrivate());
		DESKeyByte=cipher.doFinal(DESKeyByte);
		
		
		//Rigenerazione chiave DES
		DESKeySpec KS=new DESKeySpec(DESKeyByte);
		SecretKeyFactory kf=SecretKeyFactory.getInstance("DES");
		Key chiaveDES = kf.generateSecret(KS);
		
	
		//Return chiaveDES rigenerata
		return chiaveDES;
	}
	
	public String inviaComando(String command){
		command=DES.cripta(command, chiaveDES);
		pr.println(command);
		String m=null;
		
		try {
			m = br.readLine();
			String a=null;
			while(br.ready()){
				a=br.readLine();
				m += a;
			}
			m = DES.decripta(m, chiaveDES);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}
	public void chiudiInviatore(){
		String a="chiudi";
		a=DES.cripta(a, chiaveDES);
		pr.println(a);
		try {
			ServerRisto.threadAttivi--;
			br.close();
			socket.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("inviatore chiuso");
	}

	public static void main(String [] args){

	}
}